package com.atguigu.edu.realtime.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.common.base.BaseApp;
import com.atguigu.edu.realtime.common.bean.TableProcessDim;
import com.atguigu.edu.realtime.common.constant.Constant;
import com.atguigu.edu.realtime.common.util.FlinkSourceUtil;
import com.atguigu.edu.realtime.common.util.HBaseUtil;
import com.atguigu.edu.realtime.dim.function.DimSinkFunction;
import com.atguigu.edu.realtime.dim.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

public class DimApp extends BaseApp {

    public static void main(String[] args) {
        new DimApp().start(
                10002,
                4,
                "dim_app_group",
                Constant.TOPIC_DB
        );
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //1 对数据进行简单的etl
        SingleOutputStreamOperator<JSONObject> processedDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String string, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(string);
                        String database = jsonObject.getString("database");
                        String type = jsonObject.getString("type");
                        String data = jsonObject.getString("data");
                        if ("edu0422".equals(database)
                                && ("insert".equals(type)
                                || "update".equals(type)
                                || "delete".equals(type)
                                || "bootstrap-insert".equals(type))
                                && data != null
                                && data.length() > 2
                        ) {
                            collector.collect(jsonObject);
                        }
                    }
                }
        );
        //2 使用flinkCDC读取配置信息
        MySqlSource<String> mySqlSource = FlinkSourceUtil.getMySqlSource("edu0422_config", "table_process_dim");
        DataStreamSource<String> mysqlDS = env
                .fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mySqlSource")
                .setParallelism(1);

        SingleOutputStreamOperator<TableProcessDim> tableProcessDS = mysqlDS.map(
                new MapFunction<String, TableProcessDim>() {
                    @Override
                    public TableProcessDim map(String string) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(string);
                        String op = jsonObject.getString("op");
                        TableProcessDim tableProcessDim = null;
                        if ("d".equals(op)) {
                            tableProcessDim = jsonObject.getObject("before", TableProcessDim.class);
                        } else {
                            tableProcessDim = jsonObject.getObject("after", TableProcessDim.class);
                        }
                        tableProcessDim.setOp(op);
                        return tableProcessDim;
                    }
                }
        );
        //tableProcessDS.print();

        //3 根据信息在hbase中建表或者删表
        SingleOutputStreamOperator<TableProcessDim> tableProcess = tableProcessDS.map(
                new MapFunction<TableProcessDim, TableProcessDim>() {
                    @Override
                    public TableProcessDim map(TableProcessDim tableProcessDim) throws Exception {
                        Connection hBaseConnection = HBaseUtil.getHBaseConnection();
                        String op = tableProcessDim.getOp();
                        String sinkTable = tableProcessDim.getSinkTable();
                        String[] families = tableProcessDim.getSinkFamily().split(",");
                        if ("d".equals(op)) {
                            HBaseUtil.dropHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable);
                        } else if ("c".equals(op) || "r".equals(op)) {
                            HBaseUtil.createHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable, families);
                        } else {
                            HBaseUtil.dropHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable);
                            HBaseUtil.createHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable, families);
                        }
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);

        //4 广播配置流
        MapStateDescriptor<String, TableProcessDim> mapState = new MapStateDescriptor<>("mapState", String.class, TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = tableProcessDS.broadcast(mapState);
        BroadcastConnectedStream<JSONObject, TableProcessDim> connectedDS = processedDS.connect(broadcastDS);
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connectedDS.process(new TableProcessFunction(mapState));

        //5 将维度数据同步到hbase表中
        dimDS.print();
        dimDS.addSink(new DimSinkFunction());

    }
}


